/**
 * @author jstone
 */

var SamplePlayerView = new KONtx.Class({
	ClassName: 'SamplePlayerView',
	
	Extends: KONtx.system.FullscreenView,
	
	createView: function() {
		this.controls.overlay = new KONtx.control.VideoTransportOverlay().appendTo(this);

		this.player = new KONtx.videoplayer({
      viewId: this.config.viewId,
			events: {
				onStateChange: (function(event) {
					if(event.payload.newState == event.payload.videoplayer.states.STOP) {
						KONtx.application.previousView();
					}
					if(event.payload.newState == event.payload.videoplayer.states.ERROR) {
						log('');log('');log('');
						print('Received error state from video player');
						log('');log('');log('');
						this._showErrorDialog();
					}
				}).bindTo(this),
				onPlaylistEnd: (function(event) {
					KONtx.application.previousView();
				}).bindTo(this),
				onVideoLoadError: (function(event) {
					log('');log('');log('');
					print('Unable to load video. Most probably cause was no supported bitrate for this connection', $dump(event.payload, 4));
					log('');log('');log('');
					this._showErrorDialog();
				}).bindTo(this)
			}
		});
		
		
		this.player.attachAccessory(this.controls.overlay);
	},
	
	_showErrorDialog: function() {
		var self = this;
		this._errorDialog = new KONtx.dialogs.Alert({
			title: "Video Playback Error",
			message: "We encountered an error attempting to playback the requested video.",
			buttons: [
				{ label: "Ok", callback: function() {
					KONtx.application.previousView();
				} }
			] 
		});
		this._errorDialog.show();
	},
	
	focusView: function() {
		this.controls.overlay.focus();
	},
	
	updateView: function() {
		this.controls.overlay.resetState();
		try {
			this.player.changePlaylist(this.persist.playlist);
			this.player.setBandwidthBitrate(KONtx.messages.fetch("bandwidthBitrate"));
			this.player.startPlaylist();
		} catch (e) {
			log('');log('');log('');
			print("Caught an exception, so going back to sidebar", $dump(e, 3));
			log('');log('');log('');
			this._showErrorDialog();
		}
	},
	
	hideView: function() {
		this.player.detachMediaPlayerHandlers();
	}
});
